﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

/**
 * 创建时间：2014/7/15 11:56:44
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace CUWo.Common.WebHelper
{
    public class HttpGetRequestHelper
    {
        private readonly Uri _url;//网络地址
        public HttpGetRequestHelper(Uri url)
        {
            this._url = url;
        }
        // 开始异步请求
        public virtual IAsyncResult BeginRequest(AsyncCallback asyncCallback, object state)
        {
            //创建异步返回的结果对象
            AsyncResult<Stream> asyncResult = new AsyncResult<Stream>(asyncCallback, state);
            //创建web请求
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(this._url);
            //
            webRequest.Method = "GET";
            //webRequest.Headers["Date"] = DateTime.Now.ToUniversalTime().ToString("r");
            //string signContent = webRequest.Method + "\n" + webRequest.Headers["Date"] + "\n" + Uri.EscapeUriString(this._url.ToString());// Uri.EscapeDataString(this._url.ToString());// HttpUtility.HtmlEncode(this._url.ToString());
            ////
            ////signContent = "GET\nThu, 21 Aug 2014 09:15:11 GMT\nhttp://wpswww-vu-te.cloudapp.net/index.php?m=wp&c=search&q=%E4%BA%A4%E9%80%9A&p=1";
            //webRequest.Headers["Authorization"] = new HMACSHAHelper().SignHMACSHA1(signContent);
            ////LogHelper.LogInfo(signContent, this.GetType(), MethodBase.GetCurrentMethod());
            //
            AsyncCallback callback = delegate(IAsyncResult callBackResult)
            {
                try
                {
                    //设置异步操作完成
                    //asyncResult.SetAsCompleted(((HttpWebResponse)webRequest.EndGetResponse(callBackResult)).GetResponseStream(), callBackResult.CompletedSynchronously);
                    var response = webRequest.EndGetResponse(callBackResult);
                    using (var stream = response.GetResponseStream())
                    {
                        asyncResult.SetAsCompleted(stream, callBackResult.CompletedSynchronously);
                    }
                }
                catch (Exception exception)
                {
                    //发生异常也需要完成异步操作
                    asyncResult.SetAsCompleted(exception, callBackResult.CompletedSynchronously);
                }
            };
            webRequest.BeginGetResponse(callback, null);
            return asyncResult;
        }
        // 结束异步请求
        public Stream EndRequest(IAsyncResult asyncResult)
        {
            return ((AsyncResult<Stream>)asyncResult).EndInvoke();
        }
    }
}
